﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

namespace CommonModel
{
    /// <summary>
    /// 查询结果集
    /// </summary>
    /// 
    [Serializable]
    public class ResultSet<T>
    {
        public ResultSet()
        {
            Value = new List<T>();
            Total= 0;
            Footer = new List<IDictionary<string, object>>();
        }
        /// <summary>
        /// 总记录数
        /// </summary>
        public int Total { get; set; }

        public List<T> Value { get; set; }
        /// <summary>
        /// easyui Datagrid footer
        /// </summary>
        public List<IDictionary<string, object>> Footer { get; set; }
        public string ToEasyUIJson()
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            if (Value == null)
            {
                Value = new List<T>();
            }
            return JsonConvert.SerializeObject(new { total = this.Total, rows = Value, footer = Footer }, Newtonsoft.Json.Formatting.Indented, timeFormat);
        }
        /// <summary>
        /// 生成bootgrid 数据格式
        /// </summary>
        /// <param name="currentpage"></param>
        /// <param name="rowcount"></param>
        /// <returns></returns>
        public string ToBootGridJson(int currentpage, int rowcount)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            if (Value == null || Value.Count == 0)
            {
                return "{\"current\":0,\"rowCount\":0,\"total\":0,\"rows\":[]}";
            }
            return JsonConvert.SerializeObject(new { current = currentpage, rowCount = rowcount, total = this.Total, rows = Value }, Newtonsoft.Json.Formatting.Indented, timeFormat);

        }
        /// <summary>
        /// 生成bootgrid 数据格式
        /// </summary>
        /// <param name="currentpage"></param>
        /// <param name="rowcount"></param>
        /// <returns></returns>
        public string ToBootGridJson(ParamList pl)
        {
            return ToBootGridJson(pl.page, pl.rows);
        }
    }
    /// <summary>
    /// ResultSet<T> 的特例，T 的类型是IDictionary<string, object>，用于弱类型集合查询。
    /// </summary>
    [Serializable]
    public class ResultSet : ResultSet<IDictionary<string, object>>
    {
        public ResultSet():base()
        {

        }
        /// <summary>
        /// 获取一个ResultSet
        /// </summary>
        /// <param name="list"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static ResultSet GetResultSet(IEnumerable<dynamic> list, int? total = null)
        {
            var query = from m in list select MapToDictionary((IDictionary<string, object>)m);
            ResultSet rs = new ResultSet();
            rs.Value = query.ToList();
            if (total == null)
            {
                rs.Total = rs.Value.Count;
            }
            else
            {
                rs.Total = (int)total;
            }
            return rs;
        }
        public static IDictionary<string, object> MapToDictionary(IDictionary<string, object> row)
        {
            IDictionary<string, object> dic = new Dictionary<string, object>();
            foreach (var key in row.Keys)
            {
                dic.Add(key, row[key]);
            }
            return dic;
        }
        /// <summary>
        /// 根据list创建ResultSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static ResultSet GetResultSetByModelList<T>(IEnumerable<T> list)
        {
            ResultSet rs = new ResultSet();
            if (list == null || list.Count() == 0)
            {
                return rs;
            }
            rs.Total = list.Count();
            rs.Value = new List<IDictionary<string, object>>();
            foreach (var t in list)
            {
                IDictionary<string, object> dic = new Dictionary<string, object>();
                var Properties = t.GetType().GetProperties();
                foreach (var Propertie in Properties)
                {
                    if (Propertie.CanRead)
                    {
                        var pname = Propertie.Name;
                        var pvalue = Propertie.GetValue(t, null);
                        dic.Add(pname, pvalue);
                    }
                }
                rs.Value.Add(dic);
            }

            return rs;
        }



        public static ResultSet GetResultSet<T>(ResultSet<T> r)
        {
            ResultSet rs = new ResultSet();
            rs.Total = r.Total;
            rs.Value = new List<IDictionary<string, object>>();
            foreach (var t in r.Value)
            {
                IDictionary<string, object> dic = GetDictionary(t);
                rs.Value.Add(dic);
            }
            if (r.Footer != null)
            {
                rs.Footer = new List<IDictionary<string, object>>();
                rs.Footer.AddRange(r.Footer);
            }
            return rs;
        }

        public static IDictionary<string, object> GetDictionary<T>(T t)
        {
            IDictionary<string, object> dic = new Dictionary<string, object>();
            var Properties = t.GetType().GetProperties();
            foreach (var Propertie in Properties)
            {
                if (Propertie.CanRead)
                {
                    var pname = Propertie.Name;
                    var pvalue = Propertie.GetValue(t, null);
                    dic.Add(pname, pvalue);
                }
            }

            return dic;
        }

        /// <summary>
        /// 获取value 某行某列的值
        /// </summary>
        /// <param name="index"></param>
        /// <param name="col"></param>
        /// <returns></returns>
        public string GetString(int rowIndex, string colName)
        {
            if (Value.Count > rowIndex)
            {
                var v = Value[rowIndex][colName];
                if (v == null) return string.Empty;
                else
                {
                    if (v.GetType().IsEnum)
                    {
                        return ((int)v).ToString();
                    }
                    else
                    {
                        return Convert.ToString(v);
                    }
                }
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 获取某行 某列的值 object
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="colName"></param>
        /// <returns></returns>
        public object GetObject(int rowIndex, string colName)
        {
            if (Value.Count > rowIndex)
            {
                return Value[rowIndex][colName];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 为字典列添加翻译值
        /// 如 1 代表 启用 2 代表 禁用，resultset 中有一列 status 存放的是 1和2，dic 中存放 {1：启用},{2:禁用} ，新填一列叫statusName 则如下方式调用
        ///   resultset.AddTextField("status","statusName",dic);
        /// </summary>
        /// <param name="colName"></param>
        /// <param name="textName"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public ResultSet AddTextField(string colName, string textName, Dictionary<string, string> dic)
        {
            for (int i = 0; i < Value.Count; i++)
            {
                var key = GetString(i, colName);
                if (dic.ContainsKey(key))
                {
                    Value[i].Add(textName, dic[key]);
                }
                else
                {
                    Value[i].Add(textName, null);
                }
            }
            return this;
        }

        /// <summary>
        /// 给字典值添加遮罩 
        /// 如resultset 中有一列 CallNumber 存放的是电话号码，给号码添加遮罩 则如下方式调用
        ///   resultset.AddcolMask("CallNumber");
        /// </summary>
        /// <param name="colName"></param>
        /// <returns></returns>
        public ResultSet AddColMask(string colName)
        {
            for (int i = 0; i < Value.Count; i++)
            {
                var key = GetString(i, colName);

                if (!string.IsNullOrWhiteSpace(key) && key.Length > 4)
                {
                    Value[i][colName] = System.Text.RegularExpressions.Regex.Replace("**********" + key, "(.*)(.{4})(.{4})$", "$1****$3").Substring(10);
                }
            }
            return this;
        }
    }
}
